<template>
  <div>
    <el-form ref="formRef" :model="form" label-width="100px">
      <el-tree
        ref="treeRef"
        :data="treeData"
        :props="defaultProps"
        show-checkbox
        :default-expand-all="true"
        node-key="id"
        :check-strictly="true"
      />
      <el-form-item class="form-btn-row">
        <mine-button type="primary" @click="handleClose" secondary
          >取 消
        </mine-button>
        <mine-button type="primary" @click="handleConfirm">保 存 </mine-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script >
export default {
  props: {
    id: {
      type: Number,
      default: -1,
      required: true,
    },
    menuDialogVisible: {
      type: Boolean,
      default: false,
      required: true,
    },
  },
  watch: {
    menuDialogVisible: {
      handler() {
        let id = this.id;
        if (this.id != -1) {
          this.initFormData(id);
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      form: { id: -1 },
      treeData: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  methods: {
    async initFormData() {
      // 获取全部权限
      const res = await this.$store.dispatch("roleAdmin/getRoleAuthList");
      this.treeData = res.data.treeMenu;
      // 根据当行数据做权限数据回显
      const res2 = await this.$store.dispatch(
        "roleAdmin/getRoleAuthById",
        this.id
      );
      this.$refs.treeRef.setCheckedKeys(res2.data.menuIdList);
    },
    handleClose() {
      this.form = {};
      this.$emit("closeDialog");
    },
    async handleConfirm() {
      var menuIds = this.$refs.treeRef.getCheckedKeys();
      let params = {
        id: this.id,
        menuIds: menuIds,
      };

      let res = await this.$store.dispatch("roleAdmin/setRoleAuth", params);
      if (res.data.code === 200) {
        this.$message.success("保存成功");
        this.handleClose();
      } else {
        this.$message.warning("保存失败");
      }
    },
  },
};
</script>

<style scoped>
</style>
